const app = getApp();
import { jiatuiRequest, zg99Request } from "/utils/requests";
Page({
  data: {
    navTop: app.globalData.navTop,
    statusBarHeight: app.globalData.statusBarHeight,
    titleBarHeight: app.globalData.titleBarHeight,
    yl: 1,
    isShowAuth: !1,
    userInfo: null,
    my_result: null,
    index_jx: 0,
    nainjiArr: [
      {
        id: "1_1",
        text: "大一",
      },
      {
        id: "1_2",
        text: "大二",
      },
      {
        id: "1_3",
        text: "大三",
      },
      {
        id: "1_4",
        text: "大四",
      },
      {
        id: "1_5",
        text: "研一",
      },
      {
        id: "1_6",
        text: "研二",
      },
      {
        id: "1_7",
        text: "研三",
      },
    ],
    result_show: false,
    gxxx: false,
  },
  async onLoad(options) {
    this.setData(await app.methods.myPhone()); // 获取本地存储手机号
    if (!this.data.myPhone) {
      await app.methods.getPhoneNumber();
    }
    // this.setData({
    //   myPhone: 15188891862
    // })
    xhs.showShareMenu({
      shareTypes: "normal",
    });
    xhs.showLoading({
      title: "数据加载中...",
    });
    let a = this;
    xhs.getSystemInfo({
      success: function (e) {
        app.globalData || (app.globalData = {}),
          -1 !== e.model.indexOf("iPhone")
            ? (app.globalData.titleBarHeight = 44)
            : (app.globalData.titleBarHeight = 48),
          (app.globalData.statusBarHeight = e.statusBarHeight),
          a.setData({
            statusBarHeight: app.globalData.statusBarHeight,
            titleBarHeight: app.globalData.titleBarHeight,
          });
      },
      failure: function () {
        a.setData({
          statusBarHeight: 0,
          titleBarHeight: 0,
        });
      },
    });
    let links, jxOptions;
    if (options.scene) {
      options.scene = options.scene.replace(/%253D/g, ".");
      options.scene = options.scene.replace(/%2526/g, "-");
      jxOptions = await app.methods.getOPtions(options);
    }
    let id = options.scene ? jxOptions.id : options.id;
    options.id = id;
    links = await app.methods.getLink(id);
    options.fx = options.scene ? jxOptions.fx : options.fx;
    options.gh = options.scene ? jxOptions.gh : options.gh;
    options.hdid = links.hdid ? links.hdid : 1;
    this.setData({
      options,
    });
    this.setData(await app.methods.getIdentity(options)); // 获取个人身份信息
    if (this.data.getIdentity.crm) {
      options.wxh = this.data.getIdentity.crm;
    } else {
      options.wxh = options.gh;
    }
    this.setData(await app.methods.getWechat(options)); // 获取个人身份信息
    this.setData(await app.methods.guishudi(options)); // 获取归属地
    let fenbu = this.data.fenbu;
    let fenxiao = this.data.fenxiao;
    let getIdentity = this.data.getIdentity;
    getIdentity.fenbu = fenbu;
    getIdentity.fenxiao = fenxiao;
    getIdentity.zzname = this.data.zzname;
    getIdentity.zzid = this.data.zzid;
    getIdentity.erpdqm = this.data.erpdqm;
    await this.getPrices(options.hdid);
    let getUserRes = await this.isJoined();
    if (getUserRes.code == 0) {
      let authorizeInfo = await app.methods.authorizeInfo("scope.userInfo");
      this.setData({
        authorizeInfo,
        isJoined: true,
      });
    } else {
      this.setData({
        isJoined: false,
      });
    }
    if (this.data.myPhone) {
      this.setData(
        await app.methods.getphonestatusCX(
          this.data.myPhone,
          this.data.activity.actid,
          "chaxun"
        )
      );
    }
    this.setData({
      getIdentity,
    });
    xhs.showLoading({
      title: "数据加载完成",
    });
    setTimeout(() => {
      xhs.hideLoading();
    }, 1500);
    console.log(this.data);
  },

  // 获取活动信息
  getPrices(activity_id) {
    return new Promise((resolve) => {
      jiatuiRequest({
        url: `/api/v1/lottery/getActivity`,
        method: "GET",
        dataType: "jsonp",
        header: {
          "X-Requested-From": "WeChatMiniProgram",
        },
        data: {
          activity_id,
        },
      })
        .then(async (res) => {
          const { code, data } = res;
          if (code !== 0) {
            xhs.showToast({
              title: res.msg,
              icon: "fail",
              duration: 1500,
              mask: true,
            });
          }
          let { activity, prizes, participants, count } = data;
          activity.draw_time1 = this.toTs(activity.draw_time);
          this.setData({
            activity,
            prizes,
            participants,
            count,
            autoplay: prizes.length > 1 ? true : false,
            indicatorDots: prizes.length > 1 ? true : false,
          });
          if (activity.status == 1) {
            let winnerLists = await this.getWinners();
            this.setData({
              winnerLists: winnerLists.data.winnersLists,
              my_result: winnerLists.data.my_result,
            });
          }
          resolve();
        })
        .catch((err) => {
          // console.log(err)
          xhs.showToast({
            title: res.msg,
            icon: "fail",
            duration: 1500,
            mask: true,
          });
          resolve();
        });
    });
  },

  // 点击报名
  async onJoin() {
    let { myPhone } = this.data;
    if (!myPhone) {
      this.setData({
        isShowAuth: !0,
      });
      return;
    }
  },

  // 授权
  async getUserInfo(e) {
    let { userInfo, activity, myPhone } = this.data;
    if (e.detail.userInfo && e.detail.userInfo.avatarUrl) {
      userInfo = e.detail.userInfo;
      await app.methods.setStorage("userInfo", userInfo);
      // console.log(userInfo)
      if (activity.draw_status === 2) {
        xhs.showToast({
          title: "正在开奖请稍后",
          icon: "fail",
          duration: 1500,
          mask: true,
        });
        return;
      }
      if (activity.draw_status === 1) {
        xhs.showToast({
          title: "已开奖下次再来",
          icon: "fail",
          duration: 1500,
          mask: true,
        });
      }
      // 报名
      let bmRes = await this.clickSignUp(userInfo, myPhone);
      if (bmRes.code !== 0) {
        xhs.showToast({
          title: bmRes.msg,
          icon: "fail",
          duration: 1500,
          mask: true,
        });
        return;
      } else {
        xhs.showToast({
          title: "报名成功",
          icon: "success",
          duration: 1500,
          mask: true,
        });
        if (!this.data.user) {
          await app.methods.registerCX( this.data.myPhone, this.data.activity.actid, this.data.activity.name, "", this.data.getIdentity, "", "", this.data.book, "chaxun" );
          this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.activity.actid, "chaxun"));
        }
        let getParticipants = await this.getParticipantsCount();
        this.setData({
          isJoined: true,
          count: getParticipants.data.count,
          participants: getParticipants.data.participants,
        });
      }
    } else {
      let getAuthInfo = await app.methods.getAuth("scope.userInfo");
      if (getAuthInfo.errMsg !== "authorize:ok") {
        xhs.showToast({
          title: "您未授权",
          icon: "fail",
          duration: 1500,
          mask: true,
        });
        if (getAuthInfo.code == -2) {
          setTimeout(() => {
            xhs.openSetting({
              success: function (res) {
                // console.log(res)
              },
            });
          }, 1500);
        }
        return;
      }
    }
  },

  // 解析开奖时间
  toTs(drawTimeStr) {
    const utcDate = new Date(drawTimeStr);
    const pad = (n) => n.toString().padStart(2, "0");
    const year = utcDate.getFullYear();
    const month = pad(utcDate.getMonth() + 1);
    const day = pad(utcDate.getDate());
    const hours = pad(utcDate.getHours());
    const minutes = pad(utcDate.getMinutes());
    const seconds = pad(utcDate.getSeconds());
    return `${month}月${day}日 ${hours}:${minutes}:${seconds}`;
  },

  // 点击报名
  clickSignUp(userInfo, myPhone) {
    return new Promise((resolve, reject) => {
      jiatuiRequest({
        url: `/api/v1/lottery/joinActivity`,
        method: "POST",
        dataType: "jsonp",
        header: {
          "x-requested-from": "WeChatMiniProgram",
        },
        data: {
          activity_id: this.data.options.hdid,
          phone: myPhone,
          nickname: userInfo.nickName,
          avatar: userInfo.avatarUrl,
        },
      })
        .then((res) => {
          // console.log(res)
          resolve(res);
        })
        .catch((err) => {
          console.log(err);
          reject(err);
        });
    });
  },

  // 查询是否报名
  async isJoined() {
    let { myPhone } = this.data;
    return new Promise((resolve, reject) => {
      jiatuiRequest({
        url: `/api/v1/lottery/isJoined`,
        method: "GET",
        dataType: "jsonp",
        header: {
          "x-requested-from": "WeChatMiniProgram",
        },
        data: {
          activity_id: this.data.options.hdid,
          phone: myPhone,
        },
      })
        .then((res) => {
          // console.log(res)
          resolve(res);
        })
        .catch((err) => {
          // console.log(err)
          reject(err);
        });
    });
  },

  // 查询报名人数
  getParticipantsCount() {
    return new Promise((resolve, reject) => {
      jiatuiRequest({
        url: "/api/v1/lottery/getParticipantsCount",
        method: "GET",
        header: {
          "x-requested-from": "WeChatMiniProgram",
        },
        data: {
          activity_id: this.data.options.hdid,
        },
      })
        .then((res) => {
          // console.log(res)
          resolve(res);
        })
        .catch((err) => {
          // console.log(err)
          reject(err);
        });
    });
  },

  // 开奖后获取中奖信息
  getWinners: function () {
    return new Promise((resolve, reject) => {
      jiatuiRequest({
        url: "/api/v1/lottery/getWinners",
        method: "GET",
        header: {
          "x-requested-from": "WeChatMiniProgram",
        },
        data: {
          phone: this.data.myPhone,
          activity_id: this.data.options.hdid,
        },
      })
        .then((res) => {
          // console.log(res)
          resolve(res);
        })
        .catch((err) => {
          // console.log(err)
          reject(err);
        });
    });
  },

  async user_login(e) {
    if (typeof e.detail == "boolean") {
      this.setData({
        isShowAuth: e.detail,
      });
    } else {
      this.setData({
        myPhone: e.detail,
      });
      let getUserRes = await this.isJoined();
      if (getUserRes.code == 0) {
        let authorizeInfo = await app.methods.authorizeInfo("scope.userInfo");
        this.setData({
          authorizeInfo,
          isJoined: true,
        });
      } else {
        this.setData({
          isJoined: false,
        });
      }
      this.setData(
        await app.methods.getphonestatusCX(
          e.detail,
          this.data.activity.actid,
          "chaxun"
        )
      );
    }
  },

  //姓名
  nameChange: function (t) {
    this.setData({
      shname: t.detail.value,
    });
    if (!this.data.shname) {
      xhs.showToast({
        title: "请输入姓名",
        icon: "none",
        duration: 1000,
      });
      return false;
    }
    var name_re = /^[\u4e00-\u9fa5]{0,}$/;
    if (!name_re.test(this.data.shname)) {
      xhs.showToast({
        title: "请输入正确的姓名",
        icon: "none",
        duration: 1000,
      });
      return false;
    }
  },

  //地址
  addressChange: function (t) {
    this.setData({
      address: t.detail.value,
    });
    if (!this.data.address) {
      xhs.showToast({
        title: "请正确填写地址，否则无法寄出奖品呦",
        icon: "none",
        duration: 1000,
      });
      return false;
    }
  },

  //实物邮寄
  submit_address: function (jlid) {
    if (!this.data.shname) {
      xhs.showToast({
        title: "请输入姓名",
        icon: "none",
        duration: 1000,
      });
      return false;
    }
    if (!this.data.address) {
      xhs.showToast({
        title: "请输入地址",
        icon: "none",
        duration: 1000,
      });
      return false;
    }
    zg99Request({
      url: `/index/chaxun/updateuser?actid=${this.data.activity.actid}&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
      type: "GET",
      dataType: "jsonp",
      data: {
        phone: this.data.myPhone,
        shname: this.data.shname,
        address: this.data.address,
      },
    }).then((res) => {
      let resv = app.methods.getAPIReturn(res);
      xhs.showToast({
        title: "提交成功了，耐心等等快递向您奔赴吧！",
        duration: 3000,
        icon: "none",
      });
      let { user } = this.data;
      user.user.address = this.data.address;
      user.user.shname = this.data.shname;
      
      this.setData({
        result_show: false,
        user
      });
    });
  },

  // 高校活动信息提交
  gxhdtj: function (e) {
    if (!this.data.nianji || !this.data.majorvalue) {
      xhs.showToast({
        title: !this.data.nianji ? "请选择年级" : "请选择专业",
        icon: "error",
        duration: 2000,
        mask: true,
      });
      return false;
    }
    zg99Request({
      url: `/index/chaxun/updateuser/?actid=${
        this.data.activity.actid
      }&callback=&shijian=${Date.parse(new Date()) / 1e3}&`,
      type: "GET",
      dataType: "jsonp",
      data: {
        phone: this.data.myPhone,
        nianji: this.data.nianji,
        zhuanye: this.data.majorvalue,
      },
    })
      .then((res) => {
        let newStr = app.methods.getAPIReturn(res);
        // console.log(newStr)
        if (newStr.status == 1) {
          xhs.showToast({
            title: "补充信息完成",
          });
          this.setData({
            gxxx: false,
            result_show: false,
          });
        } else {
          xhs.showToast({
            title: newStr.msg,
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },

  updateUser(){
    this.setData({
      result_show: true
    })
  },

  goAll(e){
    const { id } = e.currentTarget.dataset;
    xhs.navigateTo({
      url: `./all?id=${id}`,
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { fx = "hbwtb", gh = "zcj37368", id } = this.data.options;
    let { share_img, share_font } = this.data.activity;
    return {
      title: share_font,
      path: `/packageA/lottery/index?id=${id}&fx=${fx}&gh=${gh}`,
      imageUrl: share_img,
    };
  },
});
